/**
* @file filter
* @author liaoxuezhi@baidu.com
*/
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from "react";
import { Component, PropTypes } from "react";
import { filter, fetch } from "../../renderer";
import * as cx from "classnames";
import { Enhance as FormItem } from "../form-item";
import {
    InputGroup,
    FormControl,
    Button
} from 'react-bootstrap';
import {
    alert
} from '../../../widgets/alert/alert';

@FormItem({
  type: "phone-code"
})
export default class FormStatic extends Component {
  static propTypes = {
    className: PropTypes.string,
    formMode: PropTypes.string,
    formHorizontal: PropTypes.object,
    inputClassName: PropTypes.string
  };

  static defaultProps = {
    value: "",
    placeholder: "-",
    phoneField: 'phone'
  };

  constructor(props) {
      super(props);

      this.handleChange = this.handleChange.bind(this);
      this.send = this.send.bind(this);
      this.tick = this.tick.bind(this);


      this.state = {
          wating: 0,
          sending: false
      };
  }

  componentWillUnmout() {
      clearTimeout(this.timer);
  }

  handleChange(e) {
    const {
        setValue
    } = this.props;

    setValue(e.currentTarget.value);
  }

  send() {
    const {
        sendApi,
        getValue,
        data,
        phoneField,
        onNotify
    } = this.props;

    if (!data[phoneField]) {
        return;
    }

    this.setState({
        sending: true
    });

    fetch(sendApi, data)
        .then(() => this.setState({
            sending: false,
            wating: 60
        }, this.tick))
        .catch(e => this.setState({
            sending: false
        }, () => onNotify({
            message: e.toString(),
            level: 'error'
        })));
  }

  tick() {
        if (!this.state.wating) {
            return;
        }

        this.setState({
            wating: this.state.wating -1
        });

        this.timer = setTimeout(this.tick, 1000);
  }

  render() {
    let { placeholder, value, data, disabled, inputClassName, width, height, style, phoneField } = this.props;

    style = style || {};

    width && (style.width = width);
    height && (style.height = height);

    return (
      <div className={cx("form-control-static", inputClassName)} style={style} key="input">
        <InputGroup>
          <FormControl
            disabled={disabled}
            type="text"
            value={value || ""}
            onChange={this.handleChange}
          />
          <InputGroup.Button>
            <Button disabled={disabled || this.state.wating || this.state.wating || !data[phoneField]} className="btn-info" onClick={this.send}>
              <i className="fa fa-send" /> {this.state.sending ? `发送中` : this.state.wating ? `${this.state.wating}s 重发` : `发送` }
            </Button>
          </InputGroup.Button>
        </InputGroup>
      </div>
    );
  }
}
